package com.satan.juc.demo17;

public class ThreadLocalExample {
    // 创建ThreadLocal变量
    private static final ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) {
        // 创建三个线程，每个线程都会更新ThreadLocal变量
        Thread t1 = new Thread(() -> updateThreadLocalValue(1));
        Thread t2 = new Thread(() -> updateThreadLocalValue(2));
        Thread t3 = new Thread(() -> updateThreadLocalValue(3));

        t1.start();
        t2.start();
        t3.start();
    }

    private static void updateThreadLocalValue(int increment) {
        for (int i = 0; i < 3; i++) {
            threadLocalValue.set(threadLocalValue.get() + increment);
            System.out.println("线程 " + Thread.currentThread().getName() + " 的值: " + threadLocalValue.get());
            // 模拟一些处理
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
